package com.yswee.framework.net;

import java.io.Serializable;
import java.lang.ref.WeakReference;

import com.yswee.framework.net.engine.IEngineTask;

public abstract class Entity implements Serializable {
	
	private static final long serialVersionUID = 7929675686525285388L;
	public static final int NETINVALID = -2;
	public static final int ERROR = -1;
	public static final int FINISHED = 1000;
	public static final int CENCELED = 1010;
	public static final int DOWNLOADPROGRESS = 1020;
	public static final int UPLOADPROGRESS = 1025;
	public static final int INVALID = 1030;
	public static final int NEEDLOGIN = 1050;
	
	private WeakReference<ITaskContext> context;
	
	public void setContext(ITaskContext context) {
		if(context != null) {
			this.context = new WeakReference<ITaskContext>(context);
		}
	}
	
	public ITaskContext getContext() {
		if(this.context != null) {
			return this.context.get();
		}
		return null;
	}
	
	private String baseUrl;
	
	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	private String uniqueID;

	public String getUniqueID() {
		return uniqueID;
	}

	public void setUniqueID(String uniqueID) {
		this.uniqueID = uniqueID;
	}

	private int priority = IEngineTask.DEFAULTPRIORITY;

	public int getPriority() {
		return priority;
	}

	public void setPriority(int priority) {
		if(priority > IEngineTask.MAXPRIORITY)
			priority = IEngineTask.MAXPRIORITY;
		else if(priority < IEngineTask.MINPRIORITY)
			priority = IEngineTask.MINPRIORITY;
		this.priority = priority;
	}
	
	private ITaskCondition condition;
	
	public boolean isValid() {
		if(condition != null)
			return condition.isValid();
		return true;
	}

	/**
	 * 可执行的条件（eg：当前网络为wifi）
	 * @param value
	 */
	public void setCondition(ITaskCondition value) {
		this.condition = value;
	}
	
	private boolean retryOnError = true;

	public boolean isRetryOnError() {
		return retryOnError;
	}

	/**
	 * 遇到错误后是否重试
	 * @param retryOnError
	 */
	public void setRetryOnError(boolean retryOnError) {
		this.retryOnError = retryOnError;
	}

	protected int entityStatus;

	/**
	 * 执行结果
	 * @return ERROR, FINISHED,CENCELED
	 */
	public int getEntityStatus() {
		return entityStatus;
	}

	/**
	 * 设置执行结果
	 * @param value
	 */
	public void setEntityStatus(int value) {
		this.entityStatus = value;
	}
	
	protected String message;

	/**
	 * 执行结果的信息
	 * @return
	 */
	public String getMessage() {
		return message;
	}

	protected int responseCode;

	/**
	 * http code
	 * @return ERROR, FINISHED,CENCELED
	 */
	public int getResponseCode() {
		return responseCode;
	}

	/**
	 * http code
	 * @param value
	 */
	public void setResponseCode(int value) {
		this.responseCode = value;
	}
	
	public Entity() {
		setPriority(getDefaultPriority());
	}
	
	protected int getDefaultPriority() {
		return IEngineTask.DEFAULTPRIORITY;
	}
	
	public static interface ITaskCondition {
		boolean isValid();
	}
}
